import { Controller, Get, Post, Body, Query, Req, Put, UseGuards } from '@nestjs/common';
import { UsersService } from './user.service';
import { CommonResult, validteRoles } from '../utils/result';
import { AuthGuard } from '../guard/auth.guard';
function resultJSON(val: any) {
  return JSON.stringify(val);
}

@Controller('/user')
export class UserController {
  constructor(private readonly userService: UsersService) {}

  @Get('/list')
  async getUserList(@Query() query) {
    const user = await this.userService.findUser(query.userId);
    return resultJSON(user);
  }
  @Post('/login')
  async login(@Body() body: any) {
    if (body.username === '' || body.password === '') {
      return CommonResult(null, false, 401, '用户名 ｜ 密码 让你吃了？');
    }
    const user = await this.userService.findUser(body.username);
    if (user.data == null) {
      return CommonResult(null, false, 401, '我们这没你这个人');
    }
    if (user.data.password !== body.password) {
      return CommonResult(null, false, 401, '密码错误');
    }
    // if (user.data.state === '1') {
    //   return CommonResult(null, false, 401, '该用户已登录');
    // }
    const result = await this.userService.userLogin(body);
    return CommonResult(result.data, true, 200, '登录成功');
  }

  @Post('/register')
  async register(@Body() body: any) {
    const newUser = await this.userService.findUser(body.username);
    if (newUser.data !== null) {
      return CommonResult(null, false, 401, '用户名已存在');
    }

    const result = await this.userService.createUser(body);
    return resultJSON(result);
  }

  @Get('/profile')
  @UseGuards(AuthGuard)
  getProfile(@Req() req) {
    const result = validteRoles(req);
    return result;
  }

  @Put('/setState')
  async setUserStates(@Body() body) {
    const user = await this.userService.findUser(body.username);
    this.userService.setUserState(user.data.id, body.state);
  }

  @Get('/get_email')
  @UseGuards(AuthGuard)
  async getEmail(@Query() query, @Req() req) {
    const result = await this.userService.findUserByEmails(query.username, req.user);
    return CommonResult(result, true, 200, '获取成功');
  }

  @Post('update_avatar')
  @UseGuards(AuthGuard)
  async updateAvatar(@Body() body, @Req() req) {
    const result = await this.userService.setUSerAvatar(body.avatar, req.user.id);
    return CommonResult(result, true, 200, '更换头像成功');
  }

  @Get('/getLevel')
  @UseGuards(AuthGuard)
  async getLevel(@Req() req) {
    const result = await this.userService.findUser(req.user.username);
    const date = {
      level: result.data.level,
      countLevel: result.data.countLevel,
    };
    return CommonResult(date, true, 200, '获取成功');
  }
}
